package test.test_7_23;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Objects;

/*
1, 如果存在一个Collection中存储了多个User对象,
其中有一些User数据是重复的.
获得一个包含不重复User的Collection集合
(假设只使用Collection定义的api)
 */
public class Demo02 {

    public static void main(String[] args) {
        Collection<User> coll1 = new ArrayList();
        coll1.add(new User("wzx", 97));
        coll1.add(new User("wzx", 97));
        coll1.add(new User("zx", 26));
        coll1.add(new User("sss", 78));


        Collection<User> coll2 = new ArrayList<>();
        Iterator<User> it = coll1.iterator();
        while (it.hasNext()) {
            User user = it.next();
            if (!coll2.contains(user)) {
                coll2.add(user);
            }
        }
        System.out.println(coll2);

    }
}

class User {
    String name;
    int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age && Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


